<?php 
defined('RUN_KATANA') or die('Restricted access');
require(CORE_CONFIG_PATH.'sitemap.php');
require_once(MODEL_INCLUDE_PATH.'sitemap/Site.php');
require_once(MODEL_INCLUDE_PATH.'sitemap/SitemapItem.php');
require_once(MODEL_INCLUDE_PATH.'sitemap/Article.php');
require_once(MODEL_INCLUDE_PATH.'sitemap/AutoNav.php');
class SitemapController extends ObjectController
{
	public $SiteId;
	public $StartId; 	
	public $Frontpage;
	public $DefaultPageType;
	public $SitemapItems;
	public $SubItems;
	public $MenuItems;
	
	public $CurrentPage;
	public $CurrentPageId;
	
	public $Articles;
	public $ArticleCount;
	public $CurrentArticle;
	public $CurrentArticleId;
	
	public function SitemapController() 
	{
		self::setTTL(CACHE_TTL);
		self::loadSettings();
		self::setDataTablePrefix('sitemap_');
		self::setDataTable('pages');
		
		self::setSiteId(SITE_ID);
		self::loadSitemap();
		
		if(intval($_REQUEST['article']) > 0)
		{ 
			self::setCurrentArticleId(intval($_REQUEST['article']));
			self::setViewObject('Article');
		}
		if($_REQUEST['list'] == 'article')
		{ self::setViewObject('Article'); }
		
		$this->Pager = new Pager();
	}
	
	public function getStartId() { return $this->StartId; }
	public function getSiteId() { return $this->SiteId; } 	
	public function getSubItems() { return $this->SubItems; }
	public function getSitemapItems() { return $this->SitemapItems; }
	public function getCurrentPage() { return $this->CurrentPage; }
	public function getCurrentPageId() { return $this->CurrentPageId; }
	public function getMenuItems() { return $this->MenuItems; }
	
	/* Get Articles */ 
	public function getArticle($id=0)
	{ 
		self::loadArticles();
		if($id > 0)
		{
			if(is_object($this->Articles[$id]))
			{ return $this->Articles[$id]; }
		}
	}
	public function getArticles()
	{ 
		self::loadArticles();
		return $this->Articles; 
	}
	public function getArticlesCount()
	{ 
		self::loadArticlesCount();
		return intval($this->ArticlesCount); 
	}
	public function getCurrentArticle()
	{ 
		if((!(is_object($this->CurrentArticle))) && (self::getCurrentArticleId() > 0))
		{ self::loadArticles(self::getCurrentArticleId()); }
		return $this->CurrentArticle; 
	}
	public function getCurrentArticleId() { return intval($this->CurrentArticleId); }
	/* Get Articles End */ 
	
	public function setStartId($val) { $this->StartId=$val; }
	public function setSiteId($val) { $this->SiteId=$val; } 	
	public function setSubItems($val) { $this->SubItems=$val; }
	public function setSitemapItems($val) { $this->SitemapItems=$val; }
	public function setCurrentPageId($val) { $this->CurrentPageId=$val; }
	public function setMenuItems($val) { $this->MenuItems=$val; }
	
	function loadSettings()
	{
		global $config;
		if(!self::getItemLoaded('settings'))
		{ 
			$this->Settings = $config['sitemap']; 
			self::setItemLoaded('settings', true);
		}
	}
	
	public function frontendActions()
	{
		global $katana;
		global $com;
		global $txt;
		if(self::getCurrentPageId() > 0)
		{
			if(is_object(self::getCurrentPage()))
			{ 
				self::getCurrentPage()->loadMetaData(); 
				self::loadArticles();
			}
		}
	}
	
	public function loadSitemap()
	{
		if($this->SiteId)
		{
			global $db;
			
			$sql  = 'SELECT * FROM '.DB_PERFIX.self::getDataTablePrefix().self::getDataTable().' WHERE ';
			$sql .= 'site_id='.self::getSiteId().' AND parent_id=0 ORDER BY id ASC LIMIT 1;';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, self::getTTL());
				
			if(is_array($data))
			{
				foreach($data as $row)
				{
					self::setStartId($row['id']);
					$this->Frontpage = new SitemapItem;
					if($_GET['m'] > 0)
					{ self::setCurrentPageId($_GET['m']); }
					
					$this->Frontpage->setId($row['id']);
					$this->Frontpage->setParentId($row['parent_id']);
					$this->Frontpage->setSiteId($row['site_id']);
					$this->Frontpage->setIsFrontpage($row['frontpage']);
					$this->Frontpage->setHasSubItems($row['subitems']);
					$this->Frontpage->setTitle($row['title']);
					$this->Frontpage->setImage($row['Image']);
					$this->Frontpage->setDescription($row['Description']);
					$this->Frontpage->setMetaTitle($row['MetaTitle']);
					$this->Frontpage->setAlias($row['alias']);
					$this->Frontpage->setLinkType($row['link_type']);
					$this->Frontpage->setLinkId($row['link_id']);
					$this->Frontpage->setLinkUrl($row['link_url']);
					$this->Frontpage->setLinkTarget($row['link_target']);
					$this->Frontpage->setActive($row['active']);
					$this->Frontpage->setVisible($row['visible']);
					$this->Frontpage->setAccess($row['access']);
					$this->Frontpage->setMenuOrder($row['menu_order']);
					$this->Frontpage->setThemeId($row['theme_id']);
					$this->Frontpage->setLayoutId($row['layout_id']);
					$this->Frontpage->setLevel(0);
					if($row['Image'] != '')
					{
						$this->Frontpage->ImageObject = new Image();
						$this->Frontpage->ImageObject->setFolderPath(PAGE_PATH);
						$this->Frontpage->ImageObject->setFolderUrl(PAGE_URL);
						$this->Frontpage->ImageObject->setFilename($row['image']);
					}
				}
			}
			if($this->Frontpage)
			{ self::LoadSubItems(); }
		}
	}
	
	public function LoadSubItems() 
	{
		if($this->SiteId > 0)
		{
			global $db;
			
			$sql  = 'SELECT * FROM '.DB_PERFIX.self::getDataTablePrefix().self::getDataTable().' WHERE ';
			$sql .= 'site_id='.$this->SiteId.' ORDER BY parent_id, menu_order, id ASC;';

			$result = $db->query($sql);
			$data = $db->fetch($sql, self::getTTL());
				
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->SubItems[$row['parent_id']][$row['id']] = new SitemapItem($row);
					$this->SubItems[$row['parent_id']][$row['id']]->setIsFrontpage($row['frontpage']);
					$this->SubItems[$row['parent_id']][$row['id']]->setHasSubItems($row['subitems']);
					if($row['Image'] != '')
					{
						$this->SubItems[$row['parent_id']][$row['id']]->ImageObject = new Image();
						$this->SubItems[$row['parent_id']][$row['id']]->ImageObject->setFolderPath(PAGE_PATH);
						$this->SubItems[$row['parent_id']][$row['id']]->ImageObject->setFolderUrl(PAGE_URL);
						$this->SubItems[$row['parent_id']][$row['id']]->ImageObject->setFilename($row['Image']);
					}
					if($this->CurrentPageId == $row['id'])
					{ $this->CurrentPage = $this->SubItems[$row['parent_id']][$row['id']]; }
				}
			}
			if($this->SubItems[$this->CurrentPageId])
			{ $this->CurrentPage->setSubItems($this->SubItems[$this->CurrentPageId]); }
			self::organizeSubItems();
			self::organizeSitemapItems();
			if(isset($this->CurrentPage))
			{ $this->CurrentPage->loadDetails(); }
		}
	}
	
	function loadArticles($id=0)
	{
		if(!self::getItemLoaded('Articles'.$id))
		{
			global $db;
			
			$sql  = 'SELECT * FROM '.DB_PERFIX.self::getDataTablePrefix().self::getDataTable().' WHERE ';
			$sql .= ' link_type=5';
			
			if(self::getCurrentPageId() > 0)
			{ $sql .= ' AND parent_id='.self::getCurrentPageId(); }
			
			if(self::getFrontend() > 0)
			{ $sql .= ' AND active=1'; }
				
			$sql .= ' ORDER BY menu_order, id ASC;';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, self::getTTL());
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Articles[$row['id']] = new Article($row);
					$this->Articles[$row['id']]->setIsFrontpage($row['frontpage']);
					$this->Articles[$row['id']]->setHasSubItems($row['subitems']);
					if($row['Image'] != '')
					{
						$this->Articles[$row['id']]->ImageObject = new Image();
						$this->Articles[$row['id']]->ImageObject->setFolderPath(PAGE_PATH);
						$this->Articles[$row['id']]->ImageObject->setFolderUrl(PAGE_URL);
						$this->Articles[$row['id']]->ImageObject->setFilename($row['Image']);
					}
					if((self::getCurrentArticleId() > 0) && (self::getCurrentArticleId() == $row['id']))
					{ self::setCurrentArticle($this->Articles[$row['id']]); }
				}
			}
			unset($data);
			self::setItemLoaded('Articles'.$id, true);
		}
	}
	
	private function organizeSubItems($parentid=0)
	{
		if($parentid == 0)
		{ $parentid = $this->Frontpage->Id; }
		if($parentid > 0)
		{
			if($this->SubItems[$parentid])
			{
				$items = $this->SubItems[$parentid];
				foreach(array_keys($items) as $id)
				{
					if($this->SubItems[$id])
					{
						$this->SubItems[$parentid][$id]->setSubItems($this->SubItems[$id]);
						$this->SubItems[$parentid][$id]->setSubLoaded(true);
						self::organizeSubItems($id);
					}
				}
			}
		}
	}
	
	public function organizeSitemapItems() 
	{	
		$this->SitemapItems = $this->SubItems[$this->Frontpage->ParentId][$this->Frontpage->Id];
		$this->SitemapItems->SubItems = $this->SubItems[$this->Frontpage->Id];
	}

	public function deleteSitemapItem($id)
	{
		$sql = 'DELETE FROM '.DB_PERFIX.self::getDataTablePrefix().self::getDataTable().' WHERE parent_id='.$id.';';
		$result = mysql_query($sql);
		
		$sql = 'DELETE FROM '.DB_PERFIX.self::getDataTablePrefix().self::getDataTable().' WHERE id='.$id.';';
		$result = mysql_query($sql);
	}
	
	public function getSitemapItemsXML()
	{
		global $katana;
		$out = '';
		
		self::loadSitemap();

		return $out;
	}
	
	public function cronDay()
	{ 
		if(defined('RUN_CRON'))
		{
			global $katana;
			$xmlOut = 	'<?xml version="1.0" encoding="UTF-8"?>';
			$xmlOut .= 	'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
			$xmlOut .= 	'<url>';
			$xmlOut .= 		'<loc>'.SITE_URL.'</loc>';
			$xmlOut .=		'<lastmod>'.date('Y-m-d').'</lastmod>';
			$xmlOut .= 		'<changefreq>daily</changefreq>';
			$xmlOut .= 		'<priority>1.00</priority>';
			$xmlOut .= 	'</url>';
			if($katana->ActiveCores[6])
			{ 
				global $adc;
				$xmlOut .= $adc->getSitemapItemsXML(); 
			}
			global $sitemap;
			$anav = new AutoNav($sitemap, 0, $params);
			$xmlOut .= $anav->getXML();
			$xmlOut .= 	'</urlset>';
			file_put_contents(SITE_PATH.'sitemap.xml', $xmlOut);
			return 'SitemapGenerated: '.SITE_URL.'sitemap.xml';
		}
	}
}

?>